//Request.js
//JiraClient.js
//
class JiraStatus
{
    constructor()
    {
        this.workflow = [];
        this.jiraClient = {};
    }

    async updateTransition(issueKeyOrId, finalStatus, medium)
    {
        let self = this;
        // get current can set status
        let maxLoop = 2;
        let status = {status: 502};
        let nextAction = '';

        try {
            // get issue object
            let response = await self.jiraClient.getIssue(issueKeyOrId);
            if (response.status==200) {
                let issueObject = await response.json();
                
                // init medium
                if (!medium) {
                    medium = {
                        'originStatus': issueObject.fields.status.name,
                        'cycleIndex': 0,
                        'inputStatus': finalStatus
                    };
                }

                console.log('#jira status:', {'final': finalStatus, 'current status': issueObject.fields.status.name});
                if (finalStatus.trim().toLocaleUpperCase()!==issueObject.fields.status.name.trim().toLocaleUpperCase()) {
                    // get current transition and jump to next step
                    let tResp = await self.jiraClient.getTransition(issueKeyOrId);
                    if (tResp.status==200) {
                        let tRespJson = await tResp.json();
                        let tList = {};
                        let nextId = null;
                        
                        // get allow transitions
                        tRespJson.transitions.forEach((item) => {
                            tList[item.name] = item.id;
                        });
                        console.log('#jira tList', tList);
                        // try get next step tid
                        console.log('#jira workflow', self.workflow);
                        try {
                            self.workflow.forEach((actionName, idx) => {
                                console.log('#actionName', actionName);
                                if (tList.hasOwnProperty(actionName)) {
                                    nextId = tList[actionName];
                                    nextAction = actionName;
                                    if (finalStatus==actionName) {
                                        // jump this loop
                                        throw new Error("LoopInterrupt");
                                    }
                                }
                            });
                        } catch (e) {
                            console.log('##loop', e);
                        }

                        console.log('#jira next Action', nextAction);
                        // set next transition
                        if (nextId!=null) {
                            let _tResp = await self.jiraClient.setTransition(issueKeyOrId, nextId);
                            if (_tResp.status==204) {
                                status = _tResp.status;
                                // if not match status, rollback to origin status
                                if (++medium.cycleIndex>maxLoop) {
                                    finalStatus = medium.originStatus;
                                    medium.cycleIndex = 0;
                                    medium.exception = 'Match input status fail, rollback to origin status!';
                                }
                                status = await self.updateTransition(issueKeyOrId, finalStatus, medium);
                                if (medium.exception) {
                                    delete medium.cycleIndex;
                                    console.error(medium);
                                    throw medium;
                                }
                            } else {
                                throw {'status': _tResp.status, 'func': 'set transition', 'resp': await _tResp.json()};
                            }
                        } else {
                            throw {'error':'Can not get next transition id.', 'nextId': nextId};
                        }
                    } else {
                        throw {'status':tResp.status, 'func': 'get transition', 'resp': await tResp.json()};
                    }
                }
            }
        } catch (e) {
            alert('Error! detail please see console #jira.');
            console.error('#jira', e);
        }

        return status;
    }
}

// var jiraClient = new JiraClient(JSON.parse(localStorage.getItem('config')).source);
// var jiraStatus = new JiraStatus(jiraClient);
// Task
// jiraStatus.workflow = [
//     'To Do',
//     'In Progress',
//     'Done'
// ];
//
// Bag
// jiraStatus.workflow = [
//     'Investigation',
//     'QA Confirm Request',
//     'Pass Verification',
//     'Reopen'
// ];
// jiraStatus.updateTransition('HSI-8181', 'In Progress');